'use strict';


let fs = require('fs');
let path = require('path');
let router = require('koa-router')();


function get(dir) {
    let files = fs.readdirSync(dir);

    let realfils = files.filter((name) => {
        return name.endsWith('.js') && name !== 'index.js';
    })

    return realfils;
}


function register(files, currentPath) {
    files.forEach(item => {

        let tmpPath = path.join(currentPath, item);

        let routerObj = require(tmpPath);

        for (let r in routerObj) {

            let type = routerObj[r][0];

            let fn = routerObj[r][1];

            if (type === 'get') {
                router.get(r, fn);
            } else {
                router.post(r, fn);
            }

        }
    });
}


module.exports = function (dir) {

    let x = dir || '/controllers';

    let y = path.resolve('.');

    let z = path.join(y, x);

    let files = get(z);

    register(files, z);

    return router.routes();


}